package com.iscas.green.extralindextest.controller;

import com.iscas.green.extralindextest.service.FileIOService;
import com.iscas.green.extralindextest.service.TimerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实用工具控制器，提供计时器和文件IO相关API
 */
@RestController
@RequestMapping("/api/utility")
public class UtilityController {
    
    private static final Logger log = LoggerFactory.getLogger(UtilityController.class);
    
    @Autowired
    private TimerService timerService;
    
    @Autowired
    private FileIOService fileIOService;
    
    /**
     * 启动计时器
     * 
     * @param minutes 持续时间（分钟），默认5分钟
     * @return 操作结果
     */
    @GetMapping("/timer/start")
    public ResponseEntity<Map<String, Object>> startTimer(
            @RequestParam(value = "minutes", defaultValue = "5") int minutes) {
        
        log.info("接收到启动计时器请求，持续时间: {}分钟", minutes);
        
        // 限制最大持续时间为30分钟
        if (minutes > 30) {
            minutes = 30;
            log.warn("请求的持续时间超过最大值，已调整为30分钟");
        }
        
        String result = timerService.startTimer(minutes);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", result);
        response.put("duration", minutes);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 停止计时器
     * 
     * @return 操作结果
     */
    @GetMapping("/timer/stop")
    public ResponseEntity<Map<String, Object>> stopTimer() {
        log.info("接收到停止计时器请求");
        
        String result = timerService.stopTimer();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", result);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 写入内容到文件
     * 
     * @param content 文件内容
     * @param filename 文件名（可选）
     * @return 操作结果
     */
    @PostMapping("/file/write")
    public ResponseEntity<Map<String, Object>> writeToFile(
            @RequestBody String content,
            @RequestParam(value = "filename", required = false) String filename) {
        
        log.info("接收到写入文件请求，文件名: {}", filename);
        
        String result = fileIOService.writeToFile(content, filename);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", !result.startsWith("写入文件时发生错误") && !result.startsWith("无法创建输出目录"));
        response.put("message", result);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 读取文件内容
     * 
     * @param filename 文件名
     * @return 文件内容
     */
    @GetMapping("/file/read")
    public ResponseEntity<Map<String, Object>> readFromFile(
            @RequestParam("filename") String filename) {
        
        log.info("接收到读取文件请求，文件名: {}", filename);
        
        String content = fileIOService.readFromFile(filename);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", !content.startsWith("文件不存在") && !content.startsWith("读取文件时发生错误"));
        response.put("filename", filename);
        response.put("content", content);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 列出所有文件
     * 
     * @return 文件列表
     */
    @GetMapping("/file/list")
    public ResponseEntity<Map<String, Object>> listFiles() {
        log.info("接收到列出文件请求");
        
        try {
            List<String> files = fileIOService.listFiles();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("files", files);
            response.put("count", files.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "列出文件时发生错误: " + e.getMessage());
            
            return ResponseEntity.ok(response);
        }
    }
} 